<template>
  <a-tree
    :load-data="onLoadData"
    :tree-data="treeData"
    v-model:expandedKeys="expandedKeys"
    v-model:selectedKeys="selectedKeys"
    @select="nodeSelected"
  />
</template>
<script>
import { ref, onMounted } from 'vue';
import CommonApi from '../../api/CommonApi.js'
import ConfigApi from '../../api/ConfigApi.js'

export default {
  setup() {
    const expandedKeys = ref([]);
    const selectedKeys = ref([]);
    const treeData = ref([]);

    onMounted(()=>{
      ConfigApi.get().then(response=>{
        if (response.data.code === 1) {
          // console.log(response.data.data.managePath)
          treeData.value = [{
            title: response.data.data.managePath,
            key: ''
          }]
        } else {
          this.$message.error(`数据加载失败：${response.data.message}`)
        }
      }).catch((error)=>{
        this.$message.error(`数据加载失败：${error.message}`)
      })
    })

    const onLoadData = treeNode => {
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve();
          return;
        }
        CommonApi.listFolders(treeNode.dataRef.key).then(response => {
          // console.log(response)
          if (response.data.code === 1) {
            if (response.data.data) {
              treeNode.dataRef.children = response.data.data.map(child => { 
                return {
                  title: child.title,
                  key: child.key,
                }
              })
              treeData.value = [...treeData.value];
            }
          } else {
          }
        }).then(()=>{
          resolve();
        })
      });
    };

    const nodeSelected = (selectedKeys, {selected, selectedNodes, node, event}) => {
      // console.log(selectedKeys)
    }

    const getSelected = () => {
      return selectedKeys.value
    }

    return {
      expandedKeys, selectedKeys, treeData, onLoadData,
      nodeSelected,
      getSelected
    }
  }
}
</script>